<?php
/**
 * Created by PhpStorm.
 * User: wolf
 * Date: 2018/8/27
 * Time: 15:56
 */

namespace App\Http\Controllers\MiniApp;


use App\Http\Controllers\Controller;
use App\Models\Comment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\UserCheck;
use App\Models\WeixinUser;
class CommentController extends Controller
{
    // 添加评论
    public function add(Request $request){
        $rules = [
            'shop_id'=>'required|integer|exists:shops,id',
            'order_id'=>'required|integer|exists:orders,id',
            'content'=>'required|min:5|string|max:120',
            'score'=>'required',
            'thumb'=>'string',
            'token'=>'string'
        ];
        $message = [
            'shop_id.*' => '商家信息有误',
            'order_id.*'=>'订单不存在',
            'thumb.*'=>'评价图有误',
            'score.*'=>'评分有误',
            'content.required'=>'请填写评论内容',
            'content.min'=>'评论内容太少',
            'content.max'=>'评论内容太多',
            'content.string'=>'请填写正确的评论内容',
            'token.*'=>'请传递正确的令牌'
        ];

        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $token = $request->token;
        $WeixinUser = WeixinUser::where('token',$token)->first();
        if(!$WeixinUser){
            return show(201,"无效token！");
        }else{
            $user= UserCheck::find($WeixinUser->user_id);
            if(!$user){
                return show(201,"用户不存在！");
            }
        }
        $user_id = $user->id;
        if (!$user_id){
            return  show(202,"请重新登陆");
        }
        $order_id = $request->order_id;
        $comment = Comment::where('order_id',$order_id)->first();
        if ($comment){
            return show(201,'您评论过该订单');
        }
        $thumb = $request->thumb;
        if (isset($thumb)){
            $data = array_merge(
                \request(['shop_id','order_id','content','score','thumb']),
                compact('user_id')
            );
        }else{
            $data = array_merge(
                \request(['shop_id','order_id','content','score']),
                compact('user_id')
            );
        }
        try{
            Comment::create($data);
            // 更新订单状态
            Order::where('id',$request->order_id)->update(['order_status'=>5]);
        }catch (\Exception $e){
            return show(202,'评论失败');
        }
        return show(200,'评论成功');
    }
}